/*******************************************************************************
 * Copyright (c) 2001, 2002 Boris Pruessmann and others. All rights reserved.
 * This program and the accompanying materials are made available under the
 * terms of the Common Public License v0.5 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors: Boris Pruessmann - Initial implementation.
 ******************************************************************************/
package net.sourceforge.perforce.ui.wizards;

import net.sourceforge.perforce.core.PerforceCorePlugin;
import net.sourceforge.perforce.core.api.IPerforceServer;
import net.sourceforge.perforce.core.api.IPerforceServerManager;
import net.sourceforge.perforce.ui.IPerforceUIConstants;
import net.sourceforge.perforce.ui.PerforceUIPlugin;
import net.sourceforge.perforce.ui.internal.Policy;

import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.team.core.TeamException;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @version $Revision: 488 $
 * @author <a href="mailto:bpruessmann@users.sourceforge.net">Boris Pr??mann</a>
 */
public class NewLocationWizard extends Wizard {

  /** The one and only page of this wizard. */
  private ConfigurationWizardMainPage mainPage;

  /** The connection properties */
  private Map<String, Object> properties;

  private final IPath projectPath;

  /** Constructor for NewLocationWizard. */
  public NewLocationWizard(IPath projectPath) {
    this.projectPath = projectPath;
    IDialogSettings pluginSettings = PerforceUIPlugin.getPlugin().getDialogSettings();
    IDialogSettings dialogSettings = pluginSettings.getSection("NewLocationWizard"); //$NON-NLS-1$

    if (dialogSettings == null) {
      dialogSettings = pluginSettings.addNewSection("NewLocationWizard"); //$NON-NLS-1$
    }

    setDialogSettings(dialogSettings);
    setWindowTitle(Policy.bind("NewLocationWizard.title")); //$NON-NLS-1$
  }

  /** Constructor for NewLocationWizard. */
  public NewLocationWizard() {
    this(null);
  }

  @Override
  public void addPages() {
    String heading = Policy.bind("NewLocationWizard.heading"); //$NON-NLS-1$
    mainPage =
        new ConfigurationWizardMainPage("repositoryPage1", //$NON-NLS-1$
            heading, PerforceUIPlugin.getPlugin().getImageDescriptor(
                IPerforceUIConstants.IMG_WIZBAN_SHARE));

    if (properties == null) {
      if (projectPath != null) {
        properties = PerforceCorePlugin.getServerManager().getConnectionDefaults(projectPath);
      } else {
        properties = PerforceCorePlugin.getServerManager().getConnectionDefaults();
      }
    }

    if (properties != null) {
      mainPage.setProperties(properties);
    }

    mainPage.setShowValidate(true);
    mainPage.setDescription(Policy.bind("NewLocationWizard.description")); //$NON-NLS-1$
    mainPage.setDialogSettings(getDialogSettings());
    addPage(mainPage);
  }

  @Override
  public boolean performFinish() {
    mainPage.finish(new NullProgressMonitor());
    Map<String, Object> properties = mainPage.getProperties();

    final IPerforceServer[] root = new IPerforceServer[1];
    IPerforceServerManager manager = PerforceCorePlugin.getServerManager();
    try {
      root[0] = manager.createPerforceServer(properties);
      if (mainPage.getValidate()) {
        try {
          new ProgressMonitorDialog(getShell()).run(true, true, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) throws InvocationTargetException {
              try {
                root[0].validateConnection(monitor);
              } catch (TeamException e) {
                throw new InvocationTargetException(e);
              }
            }
          });
        } catch (InterruptedException e) {
          return false;
        } catch (InvocationTargetException e) {
          Throwable t = e.getTargetException();
          if (t instanceof TeamException) {
            throw (TeamException) t;
          }
        }
      }
      manager.addPerforceServer(root[0]);
      manager.performSnapshot();
    } catch (TeamException e) {
      IStatus error = e.getStatus();
      if (root[0] == null) {
        ErrorDialog.openError(getContainer().getShell(),
            Policy.bind("NewLocationWizard.exception"), //$NON-NLS-1$
            null, error);
        return false;
      } else {
        String title = Policy.bind("NewLocationWizard.validationFailedTitle"); //$NON-NLS-1$

        String text = Policy.bind("NewLocationWizard.validationFailedText", //$NON-NLS-1$
            new Object[] {e.getStatus().getMessage()});
        boolean keep = MessageDialog.openQuestion(getContainer().getShell(), title, text);
        try {
          if (keep) {
            manager.addPerforceServer(root[0]);
          }
        } catch (TeamException e1) {
          ErrorDialog.openError(getContainer().getShell(),
              Policy.bind("exception"), null, e1.getStatus()); //$NON-NLS-1$
          return false;
        }

        return keep;
      }
    }

    return true;
  }
}
